#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import tempfile
import os
import time

class APIDebugger:
    def __init__(self, base_url="http://localhost:8080/api"):
        self.base_url = base_url
        self.session = requests.Session()
        self.access_token = None
        self.test_content_id = None
        self.test_comment_id = None
        
    def get_token(self):
        """获取登录token"""
        url = f"{self.base_url}/auth/login"
        data = {
            "usernameOrEmail": "admin2",
            "password": "123456"
        }
        
        response = self.session.post(url, json=data)
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                self.access_token = result['data']['token']
                print(f"✅ 登录成功，Token: {self.access_token[:30]}...")
                return True
        
        print(f"❌ 登录失败: {response.text}")
        return False
    
    def create_test_content(self):
        """创建测试内容"""
        print("\n🧪 创建测试内容...")
        
        # 创建测试文件
        test_content = b"Debug test content"
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
        temp_file.write(test_content)
        temp_file.flush()
        temp_file_path = temp_file.name
        
        try:
            content_data = {
                "title": "调试测试内容",
                "description": "用于调试的测试内容",
                "type": "VIDEO",
                "tags": "调试,测试",
                "published": True,
                "duration": 60
            }
            
            url = f"{self.base_url}/contents"
            headers = {'Authorization': f'Bearer {self.access_token}'}
            
            with open(temp_file_path, 'rb') as f:
                files = {
                    'file': ('debug_test.mp4', f, 'video/mp4'),
                    'content': (None, json.dumps(content_data), 'application/json')
                }
                
                response = self.session.post(url, files=files, headers=headers)
                
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    self.test_content_id = result['data']['id']
                    print(f"✅ 内容创建成功，ID: {self.test_content_id}")
                    return True
                else:
                    print(f"❌ 内容创建失败: {result.get('message')}")
            else:
                print(f"❌ 内容创建失败，状态码: {response.status_code}")
                print(f"响应: {response.text}")
                
        finally:
            try:
                os.unlink(temp_file_path)
            except:
                pass
        
        return False
    
    def debug_get_my_contents(self):
        """调试获取我的内容接口"""
        print("\n🔍 调试获取我的内容接口...")
        
        url = f"{self.base_url}/contents/my"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        # 测试不同的参数组合
        test_params = [
            {},
            {"page": 0, "size": 10},
            {"page": 0, "size": 1},
            {"page": 0, "size": 5}
        ]
        
        for i, params in enumerate(test_params, 1):
            print(f"  测试 {i}: 参数 {params}")
            try:
                response = self.session.get(url, params=params, headers=headers, timeout=10)
                print(f"    状态码: {response.status_code}")
                if response.status_code == 200:
                    result = response.json()
                    if result.get('success'):
                        content_count = len(result['data']['content'])
                        print(f"    ✅ 成功，内容数量: {content_count}")
                    else:
                        print(f"    ❌ 业务失败: {result.get('message')}")
                else:
                    print(f"    ❌ HTTP错误: {response.text[:200]}")
            except Exception as e:
                print(f"    ❌ 请求异常: {str(e)}")
    
    def debug_update_content(self):
        """调试更新内容接口"""
        print("\n🔍 调试更新内容接口...")
        
        if not self.test_content_id:
            print("  ⚠️ 没有测试内容ID，跳过")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}"
        headers = {
            'Authorization': f'Bearer {self.access_token}',
            'Content-Type': 'application/json'
        }
        
        # 测试不同的更新数据
        test_data_sets = [
            {
                "title": "更新后的标题",
                "description": "更新后的描述",
                "tags": "更新,测试",
                "published": True
            },
            {
                "title": "简单更新"
            },
            {
                "title": "完整更新",
                "description": "完整的描述更新",
                "tags": "完整,更新,测试",
                "published": False
            }
        ]
        
        for i, data in enumerate(test_data_sets, 1):
            print(f"  测试 {i}: 数据 {data}")
            try:
                response = self.session.put(url, json=data, headers=headers, timeout=10)
                print(f"    状态码: {response.status_code}")
                if response.status_code == 200:
                    result = response.json()
                    if result.get('success'):
                        print(f"    ✅ 更新成功")
                        break  # 成功后停止测试
                    else:
                        print(f"    ❌ 业务失败: {result.get('message')}")
                else:
                    print(f"    ❌ HTTP错误: {response.text[:200]}")
            except Exception as e:
                print(f"    ❌ 请求异常: {str(e)}")
    
    def debug_add_comment(self):
        """调试添加评论接口"""
        print("\n🔍 调试添加评论接口...")
        
        if not self.test_content_id:
            print("  ⚠️ 没有测试内容ID，跳过")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/comments"
        headers = {
            'Authorization': f'Bearer {self.access_token}',
            'Content-Type': 'application/json'
        }
        
        # 测试不同的评论数据
        test_comments = [
            {"content": "这是一个调试测试评论"},
            {"text": "使用text字段的评论"},
            {"content": "简短评论"},
            {"content": "这是一个比较长的评论内容，用来测试是否有长度限制或者其他验证规则"},
            {"comment": "使用comment字段"}
        ]
        
        for i, comment_data in enumerate(test_comments, 1):
            print(f"  测试 {i}: 数据 {comment_data}")
            try:
                response = self.session.post(url, json=comment_data, headers=headers, timeout=10)
                print(f"    状态码: {response.status_code}")
                if response.status_code == 200:
                    result = response.json()
                    if result.get('success'):
                        self.test_comment_id = result['data']['id']
                        print(f"    ✅ 评论成功，ID: {self.test_comment_id}")
                        break  # 成功后停止测试
                    else:
                        print(f"    ❌ 业务失败: {result.get('message')}")
                else:
                    print(f"    ❌ HTTP错误: {response.text[:200]}")
            except Exception as e:
                print(f"    ❌ 请求异常: {str(e)}")
    
    def debug_delete_content(self):
        """调试删除内容接口"""
        print("\n🔍 调试删除内容接口...")
        
        if not self.test_content_id:
            print("  ⚠️ 没有测试内容ID，跳过")
            return
        
        # 先删除评论（如果有）
        if self.test_comment_id:
            self.debug_delete_comment()
        
        url = f"{self.base_url}/contents/{self.test_content_id}"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        try:
            response = self.session.delete(url, headers=headers, timeout=10)
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"  ✅ 删除成功")
                else:
                    print(f"  ❌ 业务失败: {result.get('message')}")
            else:
                print(f"  ❌ HTTP错误: {response.text[:200]}")
        except Exception as e:
            print(f"  ❌ 请求异常: {str(e)}")
    
    def debug_delete_comment(self):
        """调试删除评论接口"""
        print("\n🔍 调试删除评论接口...")
        
        if not self.test_content_id or not self.test_comment_id:
            print("  ⚠️ 没有测试评论ID，跳过")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/comments/{self.test_comment_id}"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        try:
            response = self.session.delete(url, headers=headers, timeout=10)
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"  ✅ 评论删除成功")
                else:
                    print(f"  ❌ 业务失败: {result.get('message')}")
            else:
                print(f"  ❌ HTTP错误: {response.text[:200]}")
        except Exception as e:
            print(f"  ❌ 请求异常: {str(e)}")
    
    def run_debug(self):
        """运行完整的调试流程"""
        print("🔧 API接口调试工具")
        print("=" * 50)
        
        # 1. 登录
        if not self.get_token():
            return
        
        # 2. 创建测试内容
        self.create_test_content()
        
        # 3. 调试各个失败的接口
        self.debug_get_my_contents()
        self.debug_update_content()
        self.debug_add_comment()
        
        # 4. 清理测试数据
        print("\n🧹 清理测试数据...")
        self.debug_delete_content()
        
        print("\n✅ 调试完成!")

if __name__ == "__main__":
    debugger = APIDebugger()
    debugger.run_debug() 